//
//  LoginViewController.m
//  E_Supermarket_Slient
//
//  Created by osoons on 15/6/11.
//  Copyright (c) 2015年 E_Supermarket_Slient. All rights reserved.
//

#import "LoginViewController.h"
#import "MeranchRegisterViewController.h"
#import "ShareUserModel.h"
#import "MainTabbarController.h"
#import "JSONKit.h"
#import "Common.h"
#import "LoadingView.h"
#import "NetWarningView.h"
#import "AFNetworking.h"
#import "BaseUrlConfig.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [_v_Top.lalTitel setText:@"登录"];
    [_v_Top.btnGoback setHidden:NO];
    _v_Top.parentController = self.navigationController;
    
    [_v_Top.btnGoback removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_v_Top.btnGoback addTarget:self action:@selector(btnBack:) forControlEvents:UIControlEventTouchUpInside];
    
    [_btnLogin removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnLogin addTarget:self action:@selector(btnLogin:) forControlEvents:UIControlEventTouchUpInside];
    
    [_btnForgotPassword removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    
    [_btnForgotPassword addTarget:self action:@selector(btnForgotPassword:) forControlEvents:UIControlEventTouchUpInside];
    
    _textPhone.delegate = self;
    _textPass.delegate = self;
    
    _textPhone.returnKeyType =  UIReturnKeyNext;
    _textPhone.returnKeyType =  UIReturnKeyDefault;

    [_textPhone becomeFirstResponder];


    if (![self.string isEqualToString:@"2"]) {
        self.string = @"1";
    }
    
    // Do any additional setup after loading the view from its nib.
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    if (textField == _textPhone) {
        [_textPass becomeFirstResponder];
    }
    
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - btnLogin
-(void)btnLogin:(UIButton *)loginSingle
{
    
    
    
    
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
  

    
    
    if (_textPhone.text.length == 0) {
        
        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入登录账号" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        return ;
        
    }
    if (_textPass.text.length == 0) {
        
        UIAlertView *  alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入密码" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
        return ;
        
    }
    

    [self LoginRequestRec];
    
}

#pragma mark - btnRegister

-(void)
btnForgotPassword:(UIButton *)Register
{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
    ForgotPasswordViewController * registere = [[ForgotPasswordViewController alloc] initWithNibName:@"ForgotPasswordViewController" bundle:nil];
    
    [self presentViewController:registere animated:YES completion:^{
        
    }];
    
    
    
    
}

-(void)btnBack:(UIButton *)btnback
{

    ShareUserModel * sharemodel = [ShareUserModel shareUserModel];


    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

#pragma mark - network request

-(void)LoginRequestRec
{
    [[LoadingView shareLoadingView] show];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,loginAction];
    
    
    NSString * strPaw = [Common md5_32:_textPass.text];
    NSDictionary *params = @{
                             
                             @"loginName":[NSString stringWithFormat:@"%@",_textPhone.text],
                             @"password":strPaw,
                             @"type":self.string
                             };
    
    
    
    
    
    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
     
     
         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
     
     NSDictionary * dicRespon = responseObject;
     [self RequestSuccessWith:dicRespon];
     
     [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
     [[LoadingView shareLoadingView] dismissAnimated:YES];
     [[NetWarningView sharedNetWarningView] show];  //警告网络异常
                                                    //              NSData *doubi = operation.error    ;
                                                    //                  //     JSON格式的NSString转换成NSMutableDictionary
                                                    //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
                                                    //
                                                    //              NSError *err = nil;
                                                    //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
     NSLog(@"Error: %@", error);
     NSLog(@"请求出错了: - %@ \n%@",
           [error localizedDescription],
           [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];
    
}

-(void)RequestSuccessWith:(NSDictionary *)dicRespon
{
    
    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue==1)
        {


                    ShareUserModel * shareUser = [ShareUserModel shareUserModel];
                    [shareUser  SaveUserInfo:dicRespon WithPass:_textPass.text];
        
        
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];




            if ([self.string isEqualToString:@"2"])
            {
                [self getSellerIsAuditActionRequestRec];
            }


        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        
        MainTabbarController * view =[MainTabbarController  ShareTabBarController];
        
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:view];
        navigationController.navigationBarHidden = YES;
        window.rootViewController = navigationController;
//        [[[UIApplication sharedApplication] delegate] application:[UIApplication sharedApplication] didFinishLaunchingWithOptions:nil];
        
        
        
        }
    else
        {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];
        
        }
    
}


-(void)getSellerIsAuditActionRequestRec
{
    [[LoadingView shareLoadingView] show];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFJSONResponseSerializer serializer];//响应
    NSString *strUrl = [NSString stringWithFormat:@"%@%@",HostServer,getSellerIsAuditAction];
    ShareUserModel * shareUser = [ShareUserModel shareUserModel];
    NSDictionary *params = @{

                             @"loginName":[NSString stringWithFormat:@"%@",shareUser.user.phone],
                             @"userId":[NSString stringWithFormat:@"%@",shareUser.user.user_id],
                             @"sessionId":[NSString stringWithFormat:@"%@",shareUser.user.sessionId]

                             };




    [manager POST:strUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
     {


         //               NSData *doubi = responseObject   ;
         //                   //     JSON格式的NSString转换成NSMutableDictionary
         //               NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //               NSError *err = nil;
         //               NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

         NSDictionary * dicRespon = responseObject;
         [self getSellerIsAudituccessWith:dicRespon];

         [[LoadingView shareLoadingView] dismissAnimated:YES];
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [[LoadingView shareLoadingView] dismissAnimated:YES];
         [[NetWarningView sharedNetWarningView] show];  //警告网络异常
         //              NSData *doubi = operation.error    ;
         //                  //     JSON格式的NSString转换成NSMutableDictionary
         //              NSString *strImge =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
         //
         //              NSError *err = nil;
         //              NSDictionary *dicRespon  = [NSJSONSerialization JSONObjectWithData:[strImge dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];
         NSLog(@"Error: %@", error);
         NSLog(@"请求出错了: - %@ \n%@",
               [error localizedDescription],
               [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
     }];

}

-(void)getSellerIsAudituccessWith:(NSDictionary *)dicRespon
{

    NSString * code = [dicRespon objectForKey:@"success"];
    if (code.integerValue==1)
    {


        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];


    }
    else
    {
        [[MainTabbarController ShareTabBarController] showMessage:[dicRespon objectForKey:@"message"]];

    }

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
